<?php

/**
 * 支付宝异步接收控制器
 * @package  onlinepay
 * @version 1.0
 */

require ('core/shop.php');
quanli_include('module/base/common/quanliOnlinepay.class.php');
quanli_include('module/base/common/quanliXml.class.php');
quanli_include('module/base/system/sysPayment.class.php');

//实例支付方式类
$sysPayment = new sysPayment();

//实例xml类
$quanliXml = new quanliXml();

//实例支付类
$ebsigOnlinepay = new quanliOnlinepay();

//接收返回参数
$ebsigOnlinepay->receiveParameter();
$notify_data_array = $quanliXml->decode( $ebsigOnlinepay->getParameter('notify_data') );

//订单号
$bill_no = $notify_data_array['out_trade_no'];

//查询订单信息
$bill_array =& $G_SHOP->DBCA->stmt_query('SELECT * FROM bill_master WHERE bill_no = ?', 's', $bill_no);
if (!$bill_array) {
    die( 'fail' );
}

$pcustID = $bill_array[0]->pcustID;
$payTypeID = $bill_array[0]->payTypeID;

//查询支付方式参数
$online_parameter_array = $sysPayment->searchOnlinepPrameter( $payTypeID );

//检查签名和支付状态
$sign_str = 'service=' . $ebsigOnlinepay->getParameter('service');
$sign_str .= '&v=' . $ebsigOnlinepay->getParameter('v');
$sign_str .= '&sec_id=' . $ebsigOnlinepay->getParameter('sec_id');
$sign_str .= '&notify_data=' . $ebsigOnlinepay->getParameter('notify_data');
$sign_str .= $online_parameter_array['md5_key'];
if (md5($sign_str) != $ebsigOnlinepay->getParameter('sign') || !in_array($notify_data_array['trade_status'], array('TRADE_FINISHED', 'TRADE_SUCCESS'))) {

	//保存服务端返回数据
    $ebsigOnlinepay->setReceiveParams($bill_no, 1, 2);
	die( 'fail' );
	
}

//保存服务端返回数据
$result_code = $ebsigOnlinepay->setReceiveParams($bill_no, 1, 3);

//$result_code 1：订单在本次支付前未付款 -1：订单在本次支付前已付款
if ($result_code == 1) {
    $arg_array = array(
        'bill_no' => $bill_no,
        'pcustID' => $pcustID,
        'payTypeID' => $payTypeID,
        'billType' => 1,
        'total_amount' => $notify_data_array['total_fee'],
        'pay_code' => $notify_data_array['trade_no']
    );
    $ebsigOnlinepay->payAction( $arg_array );
}

echo 'success';